package thread;

class MyBlockingQueue{
    private String[] elem;
    private int head;
    private int tail;
    private int size;
    private Object locker = new Object();

    public MyBlockingQueue(int capacity){
        this.elem = new String[capacity];
    }

    public void put(String e) throws InterruptedException {
        synchronized (locker){
            while(this.size == this.elem.length){
                locker.wait();
            }
            this.elem[tail] = e;
            this.tail++;
            if(this.tail >= this.elem.length){
                this.tail = 0;
            }
            this.size++;
            locker.notify();
        }
    }

    public String take() throws InterruptedException {
        String ret = "";
        synchronized (locker){
            while(this.size == 0){
                locker.wait();
            }
            ret = this.elem[head];
            this.head++;
            if(this.head >= this.elem.length){
                this.head = 0;
            }
            this.size--;
            locker.notify();
        }
        return ret;
    }
}
public class ThreadDemo25 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread t1 = new Thread(() -> {
            int m = 1;
            try {
                while(true){
                    queue.put(m + "");
                    System.out.println(m + " 入队列");
                    m += 2;
                    //Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t2 = new Thread(() -> {
            int n = 2;
            try {
                while(true){
                    queue.put(n + "");
                    System.out.println(n + " 入队列");
                    n += 2;
                    //Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t3 = new Thread(() -> {
            String s = "";
            try {
                while(true){
                    s = queue.take();
                    System.out.println(s + " 出队列");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t4 = new Thread(() -> {
            String s = "";
            try {
                while(true){
                    s = queue.take();
                    System.out.println(s + " 出队列");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
